﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using WINBASE.Utils.SQLHelper;
using WINBASE.Utils.NETHelper;
using ICSharpCode.TextEditor.Document;
using Microsoft.Data.ConnectionUI;

namespace WINBASE
{
    public partial class frmTest : WLCForm
    {
        DBHandler dbHandler;
        DataConnectionDialog dcd = new DataConnectionDialog();
        DataTable dtTableList;
        DataTable dtStoreProcList;

        public frmTest()
        {
            InitializeComponent();
            InitializeUI();
            InitializeEvent();
        }

        public void InitializeUI()
        {
            Microsoft.Data.ConnectionUI.DataSource.AddStandardDataSources(dcd);
            dcd.SelectedDataSource = Microsoft.Data.ConnectionUI.DataSource.SqlDataSource;
            dcd.SelectedDataProvider = Microsoft.Data.ConnectionUI.DataProvider.SqlDataProvider;
        }

        public void InitializeEvent()
        {
            foreach (ToolStripMenuItem mySQLMenu in mnuSQL.DropDown.Items)
            {
                mySQLMenu.Click += new EventHandler(mnuSQL_ItemClicked);
            }

            foreach (ToolStripMenuItem myCSMenu in mnuCS.DropDown.Items)
            {
                myCSMenu.Click += new EventHandler(mnuCS_ItemClicked);
            }

            foreach (ToolStripMenuItem myVBMenu in mnuVB.DropDown.Items)
            {
                myVBMenu.Click += new EventHandler(mnuVB_ItemClicked);
            }
        }

        void mnuVB_ItemClicked(object sender, EventArgs e)
        {
            ToolStripMenuItem myMenu = (ToolStripMenuItem)sender;
            if (myMenu is ToolStripMenuItem)
            {
                NetHandler iNetHandler = new NetHandler(cboConString.Text);
                string path = Application.StartupPath + @"\XML";
                FileSyntaxModeProvider provider = new FileSyntaxModeProvider(path);
                HighlightingManager manager = HighlightingManager.Manager;

                manager.AddSyntaxModeFileProvider(provider);
                txtQuery.Document.HighlightingStrategy = manager.FindHighlighter("VBNET");
                txtQuery.Refresh();

                string TableName = trvTableList.SelectedNode.Text;

                switch (myMenu.Name)
                {
                    case "mnuVBBo":
                        txtQuery.Text = iNetHandler.getBO(TableName, Language.VB);
                        break;
                    case "mnuVBBll":
                        txtQuery.Text = iNetHandler.getBLL(TableName, Language.VB);
                        break;
                    case "mnuVBDal":
                        txtQuery.Text = iNetHandler.getDAL(TableName, Language.VB);
                        break;
                }

                txtQuery.ShowTabs = false;
                txtQuery.ShowSpaces = false;
                txtQuery.ShowEOLMarkers = false;
            }
        }

        void mnuCS_ItemClicked(object sender, EventArgs e)
        {
            ToolStripMenuItem myMenu = (ToolStripMenuItem)sender;
            if (myMenu is ToolStripMenuItem)
            {
                NetHandler iNetHandler = new NetHandler(cboConString.Text);
                string path = Application.StartupPath + @"\XML";
                FileSyntaxModeProvider provider = new FileSyntaxModeProvider(path);
                HighlightingManager manager = HighlightingManager.Manager;

                manager.AddSyntaxModeFileProvider(provider);
                txtQuery.Document.HighlightingStrategy = manager.FindHighlighter("CSharp");
                txtQuery.Refresh();

                string TableName = trvTableList.SelectedNode.Text;

                switch (myMenu.Name)
                {
                    case "mnuCSBo":
                        txtQuery.Text = iNetHandler.getBO(TableName, Language.CS);
                        break;
                    case "mnuCSBll":
                        txtQuery.Text = iNetHandler.getBLL(TableName, Language.CS);
                        break;
                    case "mnuCSDal":
                        txtQuery.Text = iNetHandler.getDAL(TableName, Language.CS);
                        break;
                    default: break;
                }

                txtQuery.ShowTabs = false;
                txtQuery.ShowSpaces = false;
                txtQuery.ShowEOLMarkers = false;
            }
        }

        void mnuSQL_ItemClicked(object sender, EventArgs e)
        {
            ToolStripMenuItem myMenu = (ToolStripMenuItem)sender;
            if (myMenu is ToolStripMenuItem)
            {
                SPHandler iTableHandler = new SPHandler(cboConString.Text);
                string path = Application.StartupPath + @"\XML";
                FileSyntaxModeProvider provider = new FileSyntaxModeProvider(path);
                HighlightingManager manager = HighlightingManager.Manager;

                manager.AddSyntaxModeFileProvider(provider);
                txtQuery.Document.HighlightingStrategy = manager.FindHighlighter("TSQL");
                txtQuery.Refresh();

                string TableName = trvTableList.SelectedNode.Text;
                QueryType myQType = QueryType.CREATE;

                switch (myMenu.Name)
                {
                    case "mnuSelect":
                        if (dtTableList.Select("TABLE_TYPE = 'VIEW' AND TABLE_NAME = '" + "vw_" + TableName + "'").Count() > 0)
                            myQType = QueryType.ALTER;
                        txtQuery.Text = iTableHandler.getStdViewQuery(trvTableList.SelectedNode.Text, myQType);
                        break;
                    case "mnuInsert":
                        if (dtStoreProcList.Select("name = '" + "spi_" + TableName + "'").Count() > 0)
                            myQType = QueryType.ALTER;
                        txtQuery.Text = iTableHandler.getStdProcQuery(trvTableList.SelectedNode.Text, myQType, ProcType.INSERT);
                        break;
                    case "mnuUpdate":
                        if (dtStoreProcList.Select("name = '" + "spu_" + TableName + "'").Count() > 0)
                            myQType = QueryType.ALTER;
                        txtQuery.Text = iTableHandler.getStdProcQuery(trvTableList.SelectedNode.Text, myQType, ProcType.UPDATE);
                        break;
                    case "mnuDelete":
                        if (dtStoreProcList.Select("name = '" + "spd_" + TableName + "'").Count() > 0)
                            myQType = QueryType.ALTER;
                        txtQuery.Text = iTableHandler.getStdProcQuery(trvTableList.SelectedNode.Text, myQType, ProcType.DELETE);
                        break;
                    default: break;
                }

                txtQuery.ShowTabs = false;
                txtQuery.ShowSpaces = false;
                txtQuery.ShowEOLMarkers = false;
            }
        }

        public void InitializeData() {}

        private void btnChoose_Click(object sender, EventArgs e)
        {
            if (DataConnectionDialog.Show(dcd) == DialogResult.OK)
            {
                cboConString.Items.Insert(0, dcd.ConnectionString);
                cboConString.SelectedIndex = 0;
                dbHandler = new DBHandler(cboConString.Text);
                WaitWindow.Show(WorkerMethod);
                
            }
        }

        private void WorkerMethod(object sender, WaitWindowEventArgs e)
        {
            if (dbHandler == null) return;
            if (!dbHandler.isValidConnection(dbHandler.Connection)) return;

            ControlThreadingHelper.InvokeControlAction(this, () =>
            {
                ClearFormData();
                trvTableList.Nodes[0].Text = dbHandler.Connection.Database;
                trvTableList.Nodes[0].Expand();
                trvTableList.Nodes[0].Nodes[0].ExpandAll();
                trvTableList.Update();
            });

            dtTableList = dbHandler.GetADataTable("SELECT TABLE_NAME,TABLE_TYPE FROM INFORMATION_SCHEMA.TABLES ORDER BY TABLE_NAME");
            dtStoreProcList = dbHandler.GetADataTable("SELECT name FROM sys.procedures");

            DataRow[] drTableList = dtTableList.Select("TABLE_TYPE = 'BASE TABLE'");
            for (int tindex = 0; tindex < drTableList.Count(); tindex++)
            {
                string TableName = drTableList[tindex]["TABLE_NAME"].ToString();
                TreeNode tnTable = new TreeNode(TableName);
                tnTable.ImageIndex = 2;
                tnTable.SelectedImageIndex = 2;
                tnTable.ContextMenuStrip = cmsQuery;

                DataTable dtColumnList = dbHandler.GetADataTable("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @s", TableName);
                for (int cindex = 0; cindex < dtColumnList.Rows.Count; cindex++)
                {
                    string columnName = dtColumnList.Rows[cindex]["COLUMN_NAME"].ToString();
                    TreeNode tnColumn = new TreeNode(columnName);
                    tnColumn.ImageIndex = 4;
                    tnColumn.SelectedImageIndex = 4;
                    tnTable.Nodes.Add(tnColumn);
                }

                ControlThreadingHelper.InvokeControlAction(trvTableList, () =>
                {
                    trvTableList.Nodes[0].Nodes[0].Nodes.Add(tnTable);
                    trvTableList.Update();
                });
            }

            ControlThreadingHelper.InvokeControlAction(trvTableList, () =>
            {
                if (trvTableList.Nodes[0].Nodes[0].Nodes.Count > 0)
                {
                    trvTableList.SelectedNode = trvTableList.Nodes[0].Nodes[0].Nodes[0];
                }
            });
        }

        public static class ControlThreadingHelper
        {
            public static void InvokeControlAction<t>(t control, Action action) where t : Control
            {
                if (control.InvokeRequired)
                    control.Invoke(new Action<t, Action>(InvokeControlAction), new object[] { control, action });
                else action();
            }
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            if (cboConString.Text != "" || dbHandler != null) WaitWindow.Show(WorkerMethod);
            
        }

        public void ClearFormData()
        {
            trvTableList.Nodes[0].Nodes[0].Nodes.Clear();
            txtQuery.Text = "";
        }

        private void btnExecute_Click(object sender, EventArgs e)
        {
            if (spcResult.Panel2Collapsed) pnlQuery.Padding = new Padding(0, 0, 0, 1);
            else pnlQuery.Padding = new Padding(0, 0, 0, 0);
            spcResult.Panel2Collapsed = !spcResult.Panel2Collapsed;  
        }

        private void btnCopy_Click(object sender, EventArgs e)
        {
            Clipboard.SetText(txtQuery.Text.Trim());
        }


        public Controls.WLCDataGridView DataGrid
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public Controls.WLCViewToolStrip DataGridViewFilter
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }
    }
}